package org.wu.framework.lazy.orm.database.lambda.stream.condition.update;

import org.wu.framework.core.CamelAndUnderLineConverter;
import org.wu.framework.core.ReflexUtils;
import org.wu.framework.core.utils.ObjectUtils;
import org.wu.framework.lazy.orm.core.persistence.conf.LazyTableEndpoint;
import org.wu.framework.lazy.orm.core.persistence.conf.LazyTableFieldEndpoint;
import org.wu.framework.lazy.orm.core.source.adapter.SourceFactory;
import org.wu.framework.lazy.orm.database.lambda.stream.function.Snippet;
import org.wu.framework.lazy.orm.database.lambda.stream.function.SnippetUtil;
import org.wu.framework.lazy.orm.database.lambda.stream.support.LambdaMeta;

import java.util.concurrent.ConcurrentHashMap;

public class LambdaSetBeanIgnoreEmptyBasicComparison<T> extends LambdaSetValueBasicComparison<T> {
    /**
     * 更新对象实体
     */
    private final T bean;
    // 类
    protected Class<T> classT;

    public LambdaSetBeanIgnoreEmptyBasicComparison(T bean) {
        this.bean = bean;
    }

    /**
     * 获取T 的class
     *
     * @return
     */
    @Override
    public Class<T> getClassT() {
        return (Class<T>) bean.getClass();
    }

    /**
     * 获取 set value 数据
     *
     * @return set value 数据
     */
    @Override
    public ConcurrentHashMap<String, Object> setValue() {
        ConcurrentHashMap<String, Object> concurrentHashMap = super.setValue();
        LazyTableEndpoint<?> lazyTableEndpoint = SourceFactory.defaultAnalyzeLazyTableFromClass(bean.getClass());
        for (LazyTableFieldEndpoint lazyTableFieldEndpoint : lazyTableEndpoint.getLazyTableFieldEndpointList()) {

            String columnName = lazyTableFieldEndpoint.getColumnName();
            Object declaredFieldBean = ReflexUtils.findDeclaredFieldBean(bean, lazyTableFieldEndpoint.getField());
            if(ObjectUtils.isNotEmpty(declaredFieldBean)){
                concurrentHashMap.put(columnName, declaredFieldBean);
            }

        }
        return concurrentHashMap;
    }

    /**
     * 列到字符串 表名.子段名
     *
     * @param row
     * @return 子段名
     */
    @Override
    protected String columnToString(Snippet<T, ?> row) {
        LambdaMeta lambdaMeta = SnippetUtil.extract(row);
        assert lambdaMeta != null;
        final Class<?> tClass = lambdaMeta.instantiatedClass();
        if (null == classT) {
            classT = (Class<T>) tClass;
        }
        final String methodName = lambdaMeta.methodName();
        String fieldName = CamelAndUnderLineConverter.methodToField(methodName);
        return CamelAndUnderLineConverter.humpToLine2(fieldName);
    }
}
